// api.js
import {
  getHeaders,
  getKeyData,
} from './aes.js'
// 获取当前环境
const env = process.env.NODE_ENV;
console.log(env, process.env,'环境变量');
// 获取对应环境的BASE_URL
const BASE_URL = '/api';
import showToast from '../components/toast/index.js';
// 定义错误码与消息内容的映射关系
const errorCodeMap = {
  2002: '账号或密码错误',
  1002: '权限不足',
  1003: '登录已过期',
  // 其他错误码...
};

// 封装请求方法
function request (url, method, data, headers = {}, isMsg) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method: method,
      header: Object.assign({}, uni.getStorageSync('defaultHeaders'), getHeaders(url, headers)),
      data: data,
      success: (res) => {
        res.data.data = res.data.data && getKeyData(res.data.data);
        isMsg && showToast(res.data.code == 0 ? 'success' : 'error', errorCodeMap[res.data.code] || res.data.msg);
        resolve(res.data);
      },
      fail: (err) => {
        isMsg && showToast('error', err);
        reject(err);
        console.log(err);
      }
    });
  });
}

// 封装具体的请求接口
export const getBlog = (blogId) => {
  return request('/blog/get', 'GET', {
    id: blogId
  });
};
// 封装具体的请求接口
export const getBlogList = (appId) => {
  return request('/blog/list', 'GET', {
    id: appId
  });
};
export const login = (username, password) => {
  return request('/user/login', 'POST', {
    username: username,
    password: password
  });
};
// 专家列表
export const getProfessorList = (appId) => {
  return request('/diagnose/professorList', 'GET', {
    appId: appId
  });
};
// 预约情况
export const getAppointments = (professorId) => {
  return request('/diagnose/appointments', 'GET', {
    professorId: professorId
  });
};
// 预约
export const setOrder = (order) => {
  return request('/diagnose/order', 'POST', order);
};
// 取消预约
export const delOrder = (id) => {
  return request('/diagnose/orderDel', 'GET', { id: id });
};
// 我的预约
export const myOrder = (userId) => {
  return request('/diagnose/myAppointments', 'GET', '', { userId: userId });
};
// 专家登录
export const getProfessorLogin = (userInfo) => {
  return request('/professor/login', 'POST', userInfo, {}, true)
}

// 获取专家信息
export const getProfessorInfo = (professorId) => {
  return request('/professor/get', 'GET', { id: professorId })
}
// 获取用户信息
export const getUserInfo = (userId) => {
  return request('/user/get', 'GET', { id: userId })
}

// 获取专家的预约
export const getProfessorAppointments = (professorInfo) => {
  return request('/diagnose/professorAppointments', 'GET', { timeId: professorInfo.timeId, professorId: professorInfo.professorId, date: professorInfo.date })
}

// 上传腾讯云文件
export const getKey= (bucket, region)=> {
  console.log("🚀 ~ file: http.js:105 ~ getKey ~ bucket:", bucket)
  return request('/file/getKey?bucket=' + bucket + '&region=' + region,'GET');
}
